# Replication File for
# "Behavioral Consequences of Open Candidate Recruitment"
# Authors: Jochen Rehmert


### set directory, read data, load packages
setwd("...")

# libraries
library(foreign)
library(ggplot2);library(scales)
library(pscl);library(countreg)

# generich functions
char = function(x){as.character(x)}
num = function(x){as.numeric(char(x))}

kobo.parties <- c("DPJ","LDP","YP","JRP","NPD")

dat <- read.dta("kobo_activity.dta")
dat <- dat[dat$speaker == 0 & dat$replacement == 0 & dat$drop_out == 0,]

dat$party_id <- as.character(dat$party_id)
dat$LDP <- as.numeric(dat$party_id == "LDP")
dat$DPJ <- as.numeric(dat$party_id == "DPJ")
dat$SDP <- as.numeric(dat$party_id == "SDP")
dat$YP <- as.numeric(dat$party_id == "YP")
dat$JRP <- as.numeric(dat$party_id == "JRP")

dat$margin <- as.numeric(as.character(gsub(",",".",dat$margin)))
dat$distance_diet <- as.numeric(as.character(gsub(",",".",dat$distance_diet)))


###############################################################################
#                             Table A18                                       #
###############################################################################
library(sandwich);library(lmtest);library(stargazer);library(MASS)

summary(re.1 <- glm(competed_t1 ~ LDP + SDP   + age +  term + margin + government + num_questions + num_pmbs_initiated + num_pmb_cosponsored, data = dat[which(dat$party_id %in% kobo.parties & dat$kobo == 1),], family = binomial(link = "logit")))
rows <- row.names(re.1$model)
re.1.se <- coeftest(re.1, vcov = vcovCL(re.1, cluster = dat[rows,"candidate_id"]))[,2]
coeftest(re.1, vcov = vcovCL(re.1, cluster = dat[rows,"candidate_id"]))

summary(re.2<- glm(competed_t1 ~ LDP + SDP   + age +  term + margin + government+ num_questions , data = dat[which(dat$party_id %in% kobo.parties & dat$kobo == 1),], family = binomial(link = "logit")))
rows <- row.names(re.2$model)
re.2.se <- coeftest(re.2, vcov = vcovCL(re.2, cluster = dat[rows,"candidate_id"]))[,2]
coeftest(re.2, vcov = vcovCL(re.2, cluster = dat[rows,"candidate_id"]))


summary(re.4 <- glm(competed_t1 ~ LDP + SDP + YP  + age +  term + margin + government + num_pmb_cosponsored, data = dat[which(dat$party_id %in% kobo.parties & dat$kobo == 1),], family = binomial(link = "logit")))
rows <- row.names(re.4$model)
re.4.se <- coeftest(re.4, vcov = vcovCL(re.4, cluster = dat[rows,"candidate_id"]))[,2]
coeftest(re.4, vcov = vcovCL(re.4, cluster = dat[rows,"candidate_id"]))


stargazer(list(re.1, re.2, re.4),
          se = list(re.1.se, re.2.se, re.4.se), omit = c("DPJ", "LDP","SDP", "YP"))
